import sha
import random

from django.db import models

# Create your models here.
class Captcha(models.Model):
	question = models.CharField(max_length=50)
	answer = models.IntegerField()
	key = models.CharField(max_length=50)
	
	numbers = range(1,100)
	operands = ['+','-']
	
	def generate(self):
		def random_item(lst):
			return lst[random.randint(0,len(lst)-1)]
		# create random captcha question, save to the database - return the key
		# select 2 random numbers, and the operand(random) between them - this goes in question, and
		# ends up getting displayed to the user. Answer will be what they have to enter
		first_number = random_item(self.numbers)
		second_number = random_item(self.numbers)
		# make sure there's never a negative answer
		if second_number > first_number:
			first_number,second_number = second_number,first_number
		operand = random_item(self.operands)
		self.question = "%s %s %s" % (first_number,operand,second_number)
		self.answer = eval(self.question)
		self.save()
		return self
	
	def save(self,*args,**kwargs):
		salt = sha.new(str(random.random())).hexdigest()[:5]
		key = sha.new("%s%s%s" % (salt,self.question,self.answer)).hexdigest()
		self.key = key
		super(Captcha,self).save(*args,**kwargs)